<?php

/**
 * 任务管理
 */
class action
{

    private $per_page = 30;

    /**
     * 任务列表
     *
     * @throws AnException
     */
    public function index() {

        $page_no = an_request('page_no', 1);

        $filter = array(1 => 1);
        $job_count = _model('topic_job')->getTotal(enable_filter($filter));
        if ($job_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($job_count)) {
                Response::assign('pager', $pager);
            }

            $job_list = get_data_list('topic_job', enable_filter($filter), null, $pager->getLimit($page_no));

            $now = time();

            foreach ($job_list as $key => $item) {
                $start_date = strtotime($item['start_date'] . ' 00:00:00');
                $end_date = strtotime($item['end_date'] . ' 23:59:59');
                if ($now < $start_date) {
                    $status = 0;
                } elseif ($now > $end_date) {
                    $status = 2;
                } else {
                    $status = 1;
                }
                $job_list[$key]['status'] = $status;
                $job_list[$key]['info'] = nl2br($job_list[$key]['info']);
                if ($item['term']) {
                    $term = json_decode($item['term'], 1);
                    if (!empty($term['agency_ids'])) {
                        $dealers = _uri('user', array('id' => $term['agency_ids']), 'realname');
                        $term['agency_ids'] = $dealers;
                    }
                    $job_list[$key]['term'] = $term;
                }
            }
        }

        Response::assign('job_list', $job_list);
        Response::display('admin/job_list.html');
    }

    /**
     * 添加新任务
     *
     * @alias $this->edit
     */
    public function add() {
        $this->edit();
    }

    /**
     * 编辑任务
     *
     * @throws AnException
     */
    public function edit() {
        $id = an_request('id', 0);

        $info = array();
        if ($id > 0) {
            $filter = array('id' => $id);
            $info = _model('topic_job')->read($filter);
            $info['term'] = json_decode($info['term'], true);
            if (isset($info['term']['agency_ids'])) {
                $info['term']['agency_ids'] = join("\n", $info['term']['agency_ids']);
            }
        }

        Response::assign('info', $info);
        Response::display('admin/job_edit.html');
    }

    /**
     * 保存任务
     *
     * @return array|string
     * @throws AnException
     */
    public function save() {
        $param = an_request('data', array());

        if ($param['name'] == '') {
            return '请填写任务名称';
        }

        $data = array();
        $data['name'] = $param['name'];
        $data['start_date'] = $param['start_date'];
        $data['end_date'] = $param['end_date'];
        $data['info'] = trim($param['info']);

        $param['term_agency_ids'] = trim($param['term_agency_ids']);
        if (!empty($param['term_agency_ids'])) {
            $term_agency_ids = preg_split('/[\s,]+/', $param['term_agency_ids']);
            // 验证
            $term_agency_ids = _model('user')->getFields('id', enable_filter(array(
                'id' => array_diff($term_agency_ids, array('')),
                'status' => 1,
                'dealer_level > ' => 0,
            )));
        }

        // 规则
        $term = array('agency_ids' => array());
        if (!empty($term_agency_ids)) {
            $term['agency_ids'] = $term_agency_ids;
        }

        $data['term'] = json_encode($term);

        $info = _uri('topic_job', $param['id']);
        if ($info) {
            $data['update_time'] = datetime();
            $ret = _model('topic_job')->update($info['id'], $data);
        } else {
            $data['add_time'] = datetime();
            $ret = _model('topic_job')->create($data);
        }

        if ($ret) {
            return array('保存成功', 'success', AnUrl('topic/admin/job'));
        } else {
            return '保存失败';
        }
    }

    /**
     * 删除任务
     *
     * @return array|string
     * @throws AnException
     */
    public function delete() {
        $id = an_request('id', array());

        if ($id > 0) {
            $info = _uri('topic_job', $id);
            if ($info) {
                $topic_job_total = _model('topic_job_comply')->getTotal(array('job_id' => $info['id']));
                if ($topic_job_total > 0) {
                    return '删除失败, 任务已经开始执行';
                }
                $ret = _model('topic_job')->delete($info['id']);
                if ($ret) {
                    return array('删除成功', 'success', AnUrl('topic/admin/job'));
                }
            }
        }

        return '删除失败';
    }
}